package fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.menhoo.toollibrary.common.helper.AndroidFileUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.FileUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.example.menhoo.toollibrary.common.utils.NumberUtil;
import com.example.menhoo.toollibrary.common.utils.VibrateUtil;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.MyDownload;
import application.UIApplication;
import interfaces.IDownLoadListener;
import interfaces.IReturnObject;
import mainUI.AppFragment;
import menhoo.com.i8officelibrary.R;
import model.DownloadDbModel;
import receiver.DownloadAddQueueReceiver;
import service.DownLoadService;

/**
 * 下载中  名字写错了 太麻烦就不改了
 * Created by yanglei on 15/11/12.
 */
public class UploadList extends AppFragment {
    /**
     * 是否进入编辑状态
     */
    public boolean F = false;
    public boolean isLoadingNotifyDataSetChanged = true;
    private DownloadAddQueueReceiver downloadAddQueueReceiver;

    SwipeRefreshLayout swipeLayout;

    ListView listView;

    LinearLayout toolbarBottom;

    RelativeLayout toolbarTop;

    Button buttonCancel;

    Button buttonSelectAll;

    Button buttonDelete;

    Button buttonStartDownload;

    Button buttonStopDownload;

    TextView textViewEditTitle;

    DownloadAdapter adapter;

    Map<String, View> map = new HashMap();

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContextView(R.layout.fragment_upload_list);

        getAppActivity().setDownLoadReceiverHandle(new IDownLoadListener() {
            @Override
            public void DownloadStart(Context context, Intent intent, String url, String tag) {
                if (adapter != null) {
                    adapter.downloadStart(url);
                }
            }

            @Override
            public void DownloadLoading(Context context, Intent intent, String url, long total, long current, String tag) {
                if (adapter != null) {
                    adapter.downloadLoading(url, current, total);
                }
            }

            @Override
            public void DownloadFinish(Context context, Intent intent, String url, String filePath, String tag) {
                if (adapter != null) {
                    adapter.downloadFinish(url);
                }
            }

            @Override
            public void DownloadCancelled(Context context, Intent intent, String url, String tag) {
                if (adapter != null) {
                    adapter.downloadCancelled(url);
                }
            }

            @Override
            public void DownloadError(Context context, Intent intent, String url, String errorMsg, String tag) {
                if (adapter != null) {
                    if(errorMsg.equals(DownLoadService.ONLY_WIFI_DOWNLOAD)){
                        MessageUtil.showShortToast(context,"只能wifi下载");
                    }
                    adapter.downloadError(url);
                }
            }
        });
        downloadAddQueueReceiver=new DownloadAddQueueReceiver() {
            @Override
            public void DownloadAddQueue(Context context, Intent intent, String url, String tag, String fileName, int fileSize) {
                View v = map.get(url);
                if (v == null) {
                    try {
                        DownloadDbModel item = getDB().findById(DownloadDbModel.class,url);
                        if(item!=null && adapter!=null){
                            adapter.add(item);
                        }
                    }
                    catch (Exception e){}
                }
            }
        };
    }

    @Override
    public void init() {
        super.init();
        //
        try{
            swipeLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipeLayout);
            listView = (ListView)rootView.findViewById(R.id.listView);
            toolbarBottom = (LinearLayout)rootView.findViewById(R.id.toolbarBottom);
            toolbarTop = (RelativeLayout)rootView.findViewById(R.id.toolbarTop);
            buttonCancel = (Button)rootView.findViewById(R.id.buttonCancel);
            buttonSelectAll = (Button)rootView.findViewById(R.id.buttonSelectAll);
            buttonDelete = (Button)rootView.findViewById(R.id.buttonDelete);
            buttonStartDownload = (Button)rootView.findViewById(R.id.buttonStartDownload);
            buttonStopDownload = (Button)rootView.findViewById(R.id.buttonStopDownload);
            textViewEditTitle = (TextView)rootView.findViewById(R.id.textViewEditTitle);


            buttonCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    hideToolBar();
                }
            });
            buttonSelectAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (adapter != null) {
                        adapter.SelectAll();
                    }
                }
            });
            buttonStartDownload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (adapter == null) return;

                    List<String> listUrl = adapter.getSelectUrl();

                    if (listUrl == null || listUrl.size() == 0) {
                        MessageUtil.showShortToast(context, "请选择开始下载项");
                        return;
                    }

                    for (final String url : listUrl) {

                        try{
                            final DownloadDbModel item = getDB().findById(DownloadDbModel.class,url);
                            if(item!=null){
                                getAppActivity().addDownloadQueue(item.url, item.url, UIApplication.getAppDownLoadPath
                                        (context, item.url), NumberUtil.getFileSize_KB_MB_GB(item.size), new IReturnObject() {
                                    @Override
                                    public void returnResult(Object result) {
                                        View view = map.get(item.url);
                                        if (view != null) {
                                            ViewHolder viewHolder = (ViewHolder) view.getTag();
                                            viewHolder.imageButton.setImageResource(R.mipmap.download_pause);
                                            viewHolder.imageButton.setTag(getString(R.string.wait));
                                        }
                                    }
                                });
                            }

                        }
                        catch (Exception e){
                            LogUtils.e(e.getMessage()+"");
                        }

                    }
                    hideToolBar();
                }
            });
            buttonStopDownload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (adapter == null) return;

                    List<String> listUrl = adapter.getSelectUrl();

                    if (listUrl == null || listUrl.size() == 0) {
                        MessageUtil.showShortToast(context, "请选择停止下载项");
                        return;
                    }
                    DownLoadService downLoadService = getAppActivity().getDownLoadService();
                    for (String url : listUrl) {
                        View view = map.get(url);
                        if (view != null) {
                            ViewHolder viewHolder = (ViewHolder) view.getTag();
                            viewHolder.imageButton.setImageResource(R.mipmap.download_play);
                            viewHolder.imageButton.setTag(getString(R.string.download));
                        }
                        if (downLoadService != null) {
                            downLoadService.cancelDownload(url);
                        }
                    }
                    hideToolBar();
                }
            });
            buttonDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (adapter == null) return;

                    List<DownloadDbModel> removeList = new ArrayList<>();
                    List<String> listUrl = adapter.getSelectUrl();

                    if (listUrl == null || listUrl.size() == 0) {
                        MessageUtil.showShortToast(context, "请选择删除项");
                        return;
                    }
                    DownLoadService downLoadService = getAppActivity().getDownLoadService();
                    for (String url : listUrl) {

                        try {
                            //停止正在下载的任务
                            if (downLoadService != null) {
                                downLoadService.cancelDownload(url);
                            }
                            DownloadDbModel downloadDbModel = adapter.getItem(url);
                            File deleteFile = new File(downloadDbModel.path);
                            if (deleteFile.exists()) {
                                FileUtil.deleteFile(deleteFile);
                            }
                            removeList.add(downloadDbModel);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if (removeList.size() > 0) {
                        adapter.remove(removeList);
                        try {
                            getDB().deleteAll(removeList);

                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                    if (adapter.getData().size() == 0) {
                        hideToolBar();
                        getData();
                    }
                    try {
                        MyDownload myDownload = (MyDownload) getAppActivity();
                        if (myDownload != null) {
                            myDownload.refreshSdCurrSize();
                        }
                    } catch (Exception e) {
                        LogUtils.e(e.getMessage() + "");
                    }
                }
            });

        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }


        setTitleDisplay(false);
        hideToolBar();
        this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DownloadDbModel item = (DownloadDbModel) parent.getAdapter().getItem(position);
                View v = map.get(item.url);
                if (F) {

                    if (v != null) {
                        boolean oldSelect = (boolean) v.getTag(R.id.checkBox);
                        boolean newSelect = !oldSelect;
                        v.setTag(R.id.checkBox, newSelect);
                        ImageView imageViewCheck = (ImageView) v.findViewById(R.id.imageViewCheck);
                        if (newSelect) {
                            imageViewCheck.setImageResource(R.drawable.abc_btn_check_to_on_mtrl_015);
                        } else {
                            imageViewCheck.setImageResource(R.drawable.abc_btn_check_to_on_mtrl_000);
                        }
                        List<String> list = adapter.getSelectUrl();
                        textViewEditTitle.setText("已选中" + (list != null ? list.size() : 0) + "项");
                    }
                } else {
                    final ViewHolder viewHolder = (ViewHolder) v.getTag();
                    if (viewHolder.imageButton.getTag().toString().equalsIgnoreCase(getString(R.string.download)) ||
                            viewHolder.imageButton.getTag().toString().equalsIgnoreCase(getString(R.string.retry))) {

                        getAppActivity().addDownloadQueue(item.url, item.url, UIApplication.getAppDownLoadPath
                                (context, item.url), NumberUtil.getFileSize_KB_MB_GB(item.size), new IReturnObject() {
                            @Override
                            public void returnResult(Object result) {
                                viewHolder.imageButton.setImageResource(R.mipmap.download_pause);
                                viewHolder.imageButton.setTag(getString(R.string.wait));
                            }
                        });

                    } else if (viewHolder.imageButton.getTag().toString().equalsIgnoreCase(getString(R.string.pause)) ||
                            viewHolder.imageButton.getTag().toString().equalsIgnoreCase(getString(R.string.wait))) {
                        viewHolder.imageButton.setImageResource(R.mipmap.download_play);
                        viewHolder.imageButton.setTag(getString(R.string.download));
                        //停止下载
                        DownLoadService downLoadService = getAppActivity().getDownLoadService();
                        if (downLoadService != null) {
                            downLoadService.cancelDownload(item.url);
                        }
                    }

                }
            }
        });
        this.listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                DownloadDbModel item = (DownloadDbModel) parent.getAdapter().getItem(position);

                VibrateUtil.vibrateShot(context);
                View v = map.get(item.url);
                if (v != null) {
                    v.setTag(R.id.checkBox, true);
                    List<String> list = adapter.getSelectUrl();
                    textViewEditTitle.setText("已选中" + (list != null ? list.size() : 0) + "项");
                    showToolBar();
                }

                return false;
            }
        });
        //
        SwipeRefreshLayout.OnRefreshListener listener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        };
        swipeLayout.setOnRefreshListener(listener);
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
            }
        });
        listener.onRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        context.registerReceiver(downloadAddQueueReceiver,new IntentFilter(downloadAddQueueReceiver.Action));
    }

    @Override
    public void onPause() {
        super.onPause();
        context.unregisterReceiver(downloadAddQueueReceiver);
    }

    /**
     * 得到数据
     */
    void getData() {
        hideAll();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Date startTime = new Date();
                try {
                    final List<DownloadDbModel> list = getDB().findAll(Selector.from(DownloadDbModel.class).where("isComplete",
                            "=", false).orderBy("updateTime"));
                    if (list != null && list.size() > 0) {
                        HandlerUtil.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter = new DownloadAdapter(list);
                                listView.setAdapter(adapter);
                                swipeLayout.setRefreshing(false);
                            }
                        });
                    } else {
                        HandlerUtil.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showEmpty();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(e.getMessage() + "");
                }

                Date endTime = new Date();
                if (endTime.getTime() - startTime.getTime() < 1000) {
                    try {
                        Thread.sleep(1000 - (endTime.getTime() - startTime.getTime()));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipeLayout.setRefreshing(false);
                    }
                });

            }
        }).start();
    }

    private void showToolBar() {
        toolbarTop.setVisibility(View.VISIBLE);
        toolbarBottom.setVisibility(View.VISIBLE);
        swipeLayout.setEnabled(false);
        F = true;
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    public void hideToolBar() {
        toolbarTop.setVisibility(View.GONE);
        toolbarBottom.setVisibility(View.GONE);
        swipeLayout.setEnabled(true);
        F = false;
        if (adapter != null) {
            adapter.clearSelect();
        }
    }





    class DownloadAdapter extends BaseAdapter {
        List<DownloadDbModel> data = null;

        public DownloadAdapter() {
            this.data = new ArrayList<DownloadDbModel>();
        }

        public DownloadAdapter(List<DownloadDbModel> data) {
            this.data = data;
        }

        public void add(List<DownloadDbModel> data) {
            if (this.data != null) {
                this.data.addAll(data);
                notifyDataSetChanged();
            }
        }
        public void add(DownloadDbModel item) {
            if (this.data != null) {
                this.data.add(item);
                notifyDataSetChanged();
            }
        }

        public void delete(String url) {
            if (this.data != null) {
                for (DownloadDbModel item : data) {
                    if (item.url.equalsIgnoreCase(url)) {
                        data.remove(item);
                        if(map.containsKey(item.url)){
                            map.remove(item.url);
                        }
                        notifyDataSetChanged();
                        return;
                    }
                }
            }
        }

        @Override
        public int getCount() {
            if (this.data != null) {
                return this.data.size();
            } else {
                return 0;
            }

        }


        @Override
        public DownloadDbModel getItem(int position) {
            if (this.data != null) {
                return this.data.get(position);
            } else {
                return null;
            }

        }

        public List<DownloadDbModel> getData() {
            return this.data;
        }

        public void remove(List<DownloadDbModel> list) {
            for (DownloadDbModel item : list) {
                if (map.containsKey(item.url)) {
                    map.remove(item.url);
                }
            }
            this.getData().removeAll(list);
        }

        public DownloadDbModel getItem(String url) {
            if (this.data != null) {
                for (DownloadDbModel item : data) {
                    if (item.url.equalsIgnoreCase(url)) {
                        return item;
                    }
                }
                return null;
            } else {
                return null;
            }

        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void downloadStart(final String url) {
            View v = map.get(url);
            if (v != null) {
                ViewHolder viewHolder = (ViewHolder) v.getTag();

                viewHolder.imageButton.setImageResource(R.mipmap.download_pause);
                viewHolder.imageButton.setTag(getString(R.string.pause));
                isLoadingNotifyDataSetChanged=true;

                try {
                    MyDownload myDownload = (MyDownload) getAppActivity();
                    if (myDownload != null) {
                        myDownload.refreshSdCurrSize();
                    }
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                }

                notifyDataSetChanged();
            }

        }

        public void downloadLoading(String url, long current, long total) {
            View v = map.get(url);
            if (v != null) {
                ViewHolder viewHolder = (ViewHolder) v.getTag();
                float val = (((current / 1F) / total));
                viewHolder.progress.setProgress((int)(val*100));
                viewHolder.textViewCurrSize.setText(NumberUtil.getFileSize_KB_MB_GB(current));
                viewHolder.imageButton.setImageResource(R.mipmap.download_pause);
                viewHolder.imageButton.setTag(getString(R.string.pause));
                if (!F && isLoadingNotifyDataSetChanged) {
                    notifyDataSetChanged();
                    isLoadingNotifyDataSetChanged = false;
                }
                try {
                    MyDownload myDownload = (MyDownload) getAppActivity();
                    if (myDownload != null) {
                        myDownload.refreshSdCurrSize();
                    }
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                }
            }

        }

        public void downloadFinish(String url) {
            View v = map.get(url);
            isLoadingNotifyDataSetChanged=true;
            delete(url);

            if (data == null || data.size() == 0) {
                showEmpty();
            }

            try {
                MyDownload myDownload = (MyDownload) getAppActivity();
                if (myDownload != null) {
                    myDownload.refreshSdCurrSize();
                    myDownload.setRefreshDownloadList(true);
                }
            } catch (Exception e) {
                LogUtils.e(e.getMessage() + "");
            }

        }

        public void downloadCancelled(final String url) {
            View v = map.get(url);
            if (v != null) {
                ViewHolder viewHolder = (ViewHolder) v.getTag();
                viewHolder.imageButton.setImageResource(R.mipmap.download_play);
                viewHolder.imageButton.setTag(getString(R.string.download));
                notifyDataSetChanged();
            }
        }

        public void downloadError(final String url) {
            View v = map.get(url);
            if (v != null) {
                ViewHolder viewHolder = (ViewHolder) v.getTag();
                viewHolder.imageButton.setImageResource(R.mipmap.download_play);
                viewHolder.imageButton.setTag(getString(R.string.retry));
                notifyDataSetChanged();
            }
        }

        public void clearSelect() {
            for (View v : map.values()) {
                v.setTag(R.id.checkBox, false);
            }
            notifyDataSetChanged();
        }

        public void SelectAll() {
            for (View v : map.values()) {
                v.setTag(R.id.checkBox, true);
            }
            notifyDataSetChanged();
        }

        public List<String> getSelectUrl() {
            List<String> list = new ArrayList<>();
            for (String url : map.keySet()) {
                View v = map.get(url);
                boolean isSelect = (boolean) v.getTag(R.id.checkBox);
                if (isSelect) {
                    list.add(url);
                }
            }
            return list.size() > 0 ? list : null;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final DownloadDbModel model = getItem(position);
            ViewHolder viewHolder = null;
            if (map.containsKey(model.url)) {
                convertView = map.get(model.url);
                viewHolder = (ViewHolder) convertView.getTag();
            } else {
                convertView = getLayoutInflater().inflate(R.layout.fragment_upload_list_item, null);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
                viewHolder.imageViewCheck = (ImageView) convertView.findViewById(R.id.imageViewCheck);
                viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
                viewHolder.textViewSize = (TextView) convertView.findViewById(R.id.textViewSize);
                viewHolder.linearLayoutCheck = (LinearLayout) convertView.findViewById(R.id.linearLayoutCheck);
                viewHolder.linearLayoutBtn = (LinearLayout) convertView.findViewById(R.id.linearLayoutBtn);
                viewHolder.imageButton = (ImageView) convertView.findViewById(R.id.imageButton);
                viewHolder.textViewCurrSize = (TextView) convertView.findViewById(R.id.textViewCurrSize);
                viewHolder.progress = (ProgressBar) convertView.findViewById(R.id.progress);
                if (model.status.equalsIgnoreCase("stop")) {
                    viewHolder.imageButton.setImageResource(R.mipmap.download_play);
                    viewHolder.imageButton.setTag(getString(R.string.download));
                } else if (model.status.equalsIgnoreCase("start")) {
                    viewHolder.imageButton.setImageResource(R.mipmap.download_pause);
                    viewHolder.imageButton.setTag(getString(R.string.wait));
                }
                viewHolder.progress.setProgress((int)(model.currDownloadSize/1.0f/model.size*100));
                viewHolder.textViewCurrSize.setText(NumberUtil.getFileSize_KB_MB_GB(model.currDownloadSize));
                viewHolder.progress.setMax(100);

                convertView.setTag(viewHolder);
                convertView.setTag(R.id.checkBox, false);
                convertView.setTag(R.id.query, model.path);

                map.put(model.url, convertView);
            }


            viewHolder.imageView.setImageResource(AndroidFileUtil.getFileIconRID(model.name));

            if (F) {
                viewHolder.linearLayoutCheck.setVisibility(View.VISIBLE);
                viewHolder.linearLayoutBtn.setVisibility(View.GONE);
                //恢复选中状态
                boolean isSelect = (boolean) convertView.getTag(R.id.checkBox);
                if (isSelect) {
                    viewHolder.imageViewCheck.setImageResource(R.drawable.abc_btn_check_to_on_mtrl_015);
                } else {
                    viewHolder.imageViewCheck.setImageResource(R.drawable.abc_btn_check_to_on_mtrl_000);
                }
            } else {
                viewHolder.linearLayoutCheck.setVisibility(View.GONE);
                viewHolder.linearLayoutBtn.setVisibility(View.VISIBLE);
            }

            viewHolder.textView.setText(model.name);
            viewHolder.textViewSize.setText(NumberUtil.getFileSize_KB_MB_GB(model.size));

            return convertView;
        }

    }

    class ViewHolder {
        ImageView imageView, imageViewCheck;
        TextView textView,textViewCurrSize,textViewSize;
        LinearLayout linearLayoutCheck;
        LinearLayout linearLayoutBtn;

        ImageView imageButton;

        ProgressBar progress;
    }
}
